package com.zyzg.domain;

import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;

@Data
public class Position {

    private static final long serialVersionUID = 1L;
    // 缓存键
    private String cacheKey;
    // 城市编码
    private String cityCode;
    // 区域编码
    private String adcode;
    // 省份
    private String province;
    // 城市
    private String city;

    // 区县
    private String district;

    // 当前位置
    private String curAddress;

    public Position(String cacheKey, String cityCode, String adcode, String province, String city, String district, String curAddress) {
        this.cacheKey = cacheKey;
        this.cityCode = cityCode;
        this.adcode = adcode;
        this.province = province;
        this.city = city;
        this.district = district;
        this.curAddress = curAddress;
    }

    public Position(String cacheKey, JSONObject json) {
        this.cacheKey = cacheKey;
        String  cc = "";
        try {
            JSONObject addressComponent = json.getJSONObject("addressComponent");

            cc = addressComponent.getString("city_code");
            // 额外检查内容是否为空（视业务需求）
            if (cc == null || cc.isEmpty()) {
                cc = ""; // 或设置默认值
            }
        } catch (JSONException | NullPointerException e) {
            // 记录错误日志或处理异常
            e.printStackTrace();
            cc = ""; // 确保有兜底值
        }
        if (cc.equals("")){
            cc = json.getJSONObject("addressComponent").getString("county_code");
            if (cc == null || cc.isEmpty()) {
                cc = ""; // 或设置默认值
                this.cityCode = cc;
                this.adcode = json.getJSONObject("addressComponent").getString("county_code");;
            }else{
                cc = cc.substring(0, cc.length() - 2) + "00";
                this.cityCode = cc.substring(3);
                this.adcode = json.getJSONObject("addressComponent").getString("county_code").substring(3);;
            }
        }else {
            this.cityCode = cc.substring(3);
            this.adcode = json.getJSONObject("addressComponent").getString("county_code").substring(3);;
        }
        this.province = json.getJSONObject("addressComponent").getString("province");
        this.city = json.getJSONObject("addressComponent").getString("city");
        this.district = json.getJSONObject("addressComponent").getString("county");
        this.curAddress = json.getString("formatted_address");
    }

}
